<?php

namespace app\common\library;

use think\Hook;

/**
 * 短信验证码类
 */
class Sms
{

    /**
     * 验证码有效时长
     * @var int 
     */
    protected static $expire = 120;

    /**
     * 最大允许检测的次数
     * @var int 
     */
    protected static $maxCheckNums = 10;

    /**
     * 获取最后一次手机发送的数据
     *
     * @param   int       $mobile   手机号
     * @param   string    $event    事件
     * @return  Sms
     */
    public static function get($mobile, $event = 'default')
    {
        $sms = \app\common\model\Sms::
                where(['mobile' => $mobile, 'event' => $event])
                ->order('id', 'DESC')
                ->find();
        //Hook::listen('sms_get', $sms, null, true);
        return $sms ? $sms : NULL;
    }

    /**
     * 发送验证码
     *
     * @param   int       $mobile   手机号
     * @param   int       $code     验证码,为空时将自动生成4位数字
     * @param   string    $event    事件
     * @return  boolean
     */
    public static function send($mobile, $code = NULL, $event = 'default')
    {
        $code = is_null($code) ? mt_rand(1000, 9999) : $code;
        $time = time();
        $ip = request()->ip();
        $sms = \app\common\model\Sms::create(['event' => $event, 'mobile' => $mobile, 'code' => $code, 'ip' => $ip, 'createtime' => $time]);
        $result = Hook::listen('sms_send', $sms, null, true);
        if (!$result){
            $sms->delete();
            return FALSE;
        }
        return TRUE;
    }

    /**
     * 发送通知
     * 
     * @param   mixed     $mobile   手机号,多个以,分隔
     * @param   string    $msg      消息内容
     * @param   string    $template 消息模板
     * @return  boolean
     */
    public static function notice($mobile, $msg = '', $template = NULL)
    {
        $params = [
            'mobile'   => $mobile,
            'msg'      => $msg,
            'template' => $template
        ];
        $result = Hook::listen('sms_notice', $params, null, true);
        return $result ? TRUE : FALSE;
    }

    /**
     * 校验验证码
     *
     * @param   int       $mobile     手机号
     * @param   int       $code       验证码
     * @param   string    $event      事件
     * @return  boolean
     */
    public static function check($mobile, $code, $event = 'default')
    {
        $time = time() - self::$expire;
        $sms = \app\common\model\Sms::where(['mobile' => $mobile, 'event' => $event])
                ->order('id', 'DESC')
                ->find();
        if ($sms)
        {
            if ($sms['createtime'] > $time && $sms['times'] <= self::$maxCheckNums)
            {
                $correct = $code == $sms['code'];
                if (!$correct)
                {
                    $sms->times = $sms->times + 1;
                    $sms->save();
                    return FALSE;
                }
                else
                {
                    $result = Hook::listen('sms_check', $sms, null, true);
                    return $result;
                }
            }
            else
            {
                // 过期则清空该手机验证码
                self::flush($mobile, $event);
                return FALSE;
            }
        }
        else
        {
            return FALSE;
        }
    }

    /**
     * 清空指定手机号验证码
     *
     * @param   int       $mobile     手机号
     * @param   string    $event      事件
     * @return  boolean
     */
    public static function flush($mobile, $event = 'default')
    {
        \app\common\model\Sms::
                where(['mobile' => $mobile, 'event' => $event])
                ->delete();
        Hook::listen('sms_flush');
        return TRUE;
    }
    /**
     * 发送短信
     * 
     */
    public static function sendsms($mobile, $message, $word = 0, $time = 0){
        $word or $word = self::word_count($message);
        $message3 = iconv("UTF-8","gb2312",$message."【万木合春】");
        $flag = 0;
        $argv = Array(
            "sn" => "SDK-BBX-010-15936",
            "pwd" => strtoupper(md5('SDK-BBX-010-15936'.'AA8cb8b-')),
            "mobile" => $mobile,
            "content" => $message3,
            "ext" => "",
            "stime" => "",
            "rrid" => ""
        );
        $params='';
        foreach ($argv as $key=>$value) {
            if ($flag!=0) {
                $params .= "&";
                $flag = 1;
            }
            $params.= $key."="; $params.=urlencode($value);
            $flag = 1;
        }
        $length = strlen($params);
        $fp = fsockopen("sdk2.zucp.net",80,$errno,$errstr,10) or exit($errstr."--->".$errno);
        $header = "POST /webservice.asmx/mt HTTP/1.1\r\n";
        $header .= "Host:sdk2.zucp.net\r\n";
        $header .= "Content-Type: application/x-www-form-urlencoded\r\n";
        $header .= "Content-Length: ".$length."\r\n";
        $header .= "Connection: Close\r\n\r\n";
        $header .= $params."\r\n";
        $line = '';
        fputs($fp,$header);
        while(!feof($fp)){
            $line .= fgets($fp,1024);
        }
        list(,$line)=explode("\r\n\r\n",$line,2);
        $line=str_replace("<string xmlns=\"http://tempuri.org/\">","",$line);
        $line=str_replace("</string>","",$line);
        $line=preg_replace('/<[^>]*?>/','',$line);
        $line=trim($line);
        //$db->query("INSERT INTO {$db->pre}sms (mobile,message,word,editor,sendtime,code) VALUES ('$mobile','$messages','$word','$_username','$DT_TIME','$code')");
        return $line;
    }

    public static function word_count($string) {
        if(function_exists('mb_strlen')) return mb_strlen($string, 'utf-8');
        $string = convert($string, DT_CHARSET, 'gbk');
        $length = strlen($string);
        $count = 0;
        for($i = 0; $i < $length; $i++) {
            $t = ord($string[$i]);
            if($t > 127) $i++;
            $count++;
        }
        return $count;
    }
    public static function convert($str, $from = 'utf-8', $to = 'gb2312') {
        if(!$str) return '';
        $from = strtolower($from);
        $to = strtolower($to);
        if($from == $to) return $str;
        $from = str_replace('gbk', 'gb2312', $from);
        $to = str_replace('gbk', 'gb2312', $to);
        $from = str_replace('utf8', 'utf-8', $from);
        $to = str_replace('utf8', 'utf-8', $to);
        if($from == $to) return $str;
        $tmp = array();
        if(function_exists('iconv')) {
            if(is_array($str)) {
                foreach($str as $key => $val) {
                    $tmp[$key] = iconv($from, $to."//IGNORE", $val);
                }
                return $tmp;
            } else {
                return iconv($from, $to."//IGNORE", $str);
            }
        } else if(function_exists('mb_convert_encoding')) {
            if(is_array($str)) {
                foreach($str as $key => $val) {
                    $tmp[$key] = mb_convert_encoding($val, $to, $from);
                }
                return $tmp;
            } else {
                return mb_convert_encoding($str, $to, $from);
            }
        } else {
            //require_once DT_ROOT.'/include/convert.func.php';
            return dconvert($str, $to, $from);
        }
    }
}
